//
// Created by 86150 on 2021/10/9.
//

#ifndef BJUT_CPP_2_DB_WORKER_H
#define BJUT_CPP_2_DB_WORKER_H
#include"products.h"
#include<windows.h>
#include"winsock.h"
#include"mysql.h"

class DB_worker
{
	private:
		MYSQL mysql;
		MYSQL_RES myres;
		MYSQL_ROW myrow;

	public:
		DB_worker()
		{
			mysql_init(&mysql);
			if (mysql_real_connect(&mysql, "localhost", "root", "", "test1", 3306, NULL, 0))
				std::cout<<"\n you successfully connect this toy DB\n";
			else std::cout<<"oHHHHHHHHHHHHHH, no";
		}
		std::string stringlize(common_employee temp)
		{
			return ("(\'" + temp.get_id() + "\', \'" + temp.get_name() + "\', "
					+ "\'" + temp.get_kind() + "\', " + std::to_string(temp.get_salary()) + ")");
		}
		void insert(common_employee temp)
		{
			std::string query = "insert into Bjutcpp2 (id, name, kind, salary) values "
									+ stringlize(temp);
			mysql_query(&mysql, query.c_str());
		}//增
		void remove(std::string id)
		{
			std::string query = "delete from Bjutcpp2 where id=\"" + id + "\"";
			mysql_query(&mysql, query.c_str());
		}//删
		common_employee get(std::string id)
		{
			std::string query = "select * from Bjutcpp2 where id=\"" + id + "\"";
			mysql_query(&mysql, query.c_str());
			myres = *mysql_store_result(&mysql);
			myrow = mysql_fetch_row(&myres);

			common_employee temp(myrow[0], myrow[1], myrow[2], 0, 0, 0);
			temp.set_salary(std::stoi(myrow[3]));

			return temp;
		}//查
		void change(std::string id, common_employee temp)
		{
			std::string query1 = "update Bjutcpp2 set id=" + temp.get_id();
			std::string query2 = "update Bjutcpp2 set name=" + temp.get_name();
			std::string query3 = "update Bjutcpp2 set kind=" + temp.get_kind();
			std::string query4 = "update Bjutcpp2 set salary=" + std::to_string(temp.get_salary());

			mysql_query(&mysql, query1.c_str());
			mysql_query(&mysql, query2.c_str());
			mysql_query(&mysql, query3.c_str());
			mysql_query(&mysql, query4.c_str());
		}//改
		~DB_worker()
		{
			mysql_close(&mysql);
		}
};

#endif //BJUT_CPP_2_DB_WORKER_H
